package com.softserveinc.ita.kaiji.rest;

import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.softserveinc.ita.kaiji.dto.rest.RestGameInfoDto;
import com.softserveinc.ita.kaiji.model.Card;
import com.softserveinc.ita.kaiji.model.game.GameHistory;
import com.softserveinc.ita.kaiji.model.game.GameInfo;
import com.softserveinc.ita.kaiji.model.player.Player;
import com.softserveinc.ita.kaiji.service.GameService;
import com.softserveinc.ita.kaiji.service.GameServiceImpl;

/**
 * @author Eugene Semenkov,Boiko Eduard
 * @version 1.1.2
 * @since 17.03.14
 */

@RestController
@RequestMapping("/rest/game")
public class RestPlayGameController {

	private static Logger logger = Logger.getLogger(RestPlayGameController.class);
	private GameService gameService = new GameServiceImpl();

	@RequestMapping(value = "/init/", method = RequestMethod.POST )
	public RestGameInfoDto initRestGame(@RequestBody RestGameInfoDto restGameInfoDto) {

		Integer gameId   		= restGameInfoDto.getGameId();
		Integer personId 		= gameService.getPlayerIdFromGame(gameId);
		GameHistory gameHistory = gameService.getGameHistory(gameId);
		GameInfo gameInfo 		= gameHistory.getGameInfo();
		Set<Player> players 	= gameInfo.getPlayers();
		
		Integer person = null;
		Integer enemy = null;
		
		for (Player player : players) {
			if (player.getId().equals(personId)) {
				person = player.getId();
			} else {
				enemy = player.getId();
			}
		}
		//restGameInfoDto.getPerson().setId(id);
		restGameInfoDto.setPersonId(person);;
		restGameInfoDto.setEnemyId(enemy);
		return restGameInfoDto;

	}

	@RequestMapping(value = "/play/", method = RequestMethod.POST)
	public GameHistory getCard(@RequestBody RestGameInfoDto restGameInfoDto) {

		Integer gameId 			= restGameInfoDto.getGameId();
		Integer  personId 		= gameService.getPlayerIdFromGame(gameId);
		Card playerChosenCard 	= Card.valueOf(restGameInfoDto.getCard());
		
		logger.info("GameId: " + gameId + ". CardId: "
				+ playerChosenCard + ". PersonId: " + personId);

		gameService.makeTurn(gameId, personId, playerChosenCard);
		GameHistory gameHistory = gameService.getGameHistory(gameId);
		return gameHistory;
	}

}
